package com.jtech.together.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.jtech.together.R;
import com.jtech.together.manager.UserManager;
import com.jtech.together.model.event.InChatEvent;
import com.jtech.together.model.event.ReceiveMessageEvent;
import com.jtech.together.mvp.contract.ChatContract;
import com.jtech.together.mvp.presenter.ChatPresenter;
import com.jtech.together.util.ActivityJump;
import com.jtech.together.util.Bus;
import com.jtech.together.util.ImageGallery;
import com.jtech.together.util.ImageSelect;
import com.jtech.together.util.JNotify;
import com.jtech.together.util.LocationSelect;
import com.jtech.together.view.activity.base.BaseActivity;
import com.jtech.together.view.adapter.ChatMessageAdapter;
import com.jtech.together.view.weight.ChatInputView;
import com.jtech.together.view.weight.ChatListView;
import com.jtech.together.view.weight.popup.AudioPlayerPopup;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;

/**
 * 聊天页面
 * Created by wuxubaiyang on 2017/5/14.
 */
public class ChatActivity extends BaseActivity implements ChatContract.View, View.OnClickListener, ChatMessageAdapter.ChatMessageListener,
        ChatInputView.ChatInputListener {
    public static final String KEY_TARGET_ID = "keyTargetId";

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.chatlistview_chat)
    ChatListView chatListView;
    @Bind(R.id.chatinputview_chat)
    ChatInputView chatInputView;

    private ChatContract.Presenter presenter;

    @Override
    protected void initVariables(Bundle bundle) {
        //上车
        Bus.getOn(this);
        //绑定P类
        presenter = new ChatPresenter(getActivity(), this, bundle);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_chat);
        //设置标题栏
        setSupportActionBar(toolbar);
        //设置按钮点击
        toolbar.setNavigationOnClickListener(this);
        //设置聊天列表监听
        chatListView.setChatMessageListener(this);
        //设置聊天控制器监听
        chatInputView.setChatInputListener(this);
        //绑定键盘控制
        chatInputView.attach(getActivity());
    }

    @Override
    protected void loadData() {
        //获取目标用户对象
        BmobIMUserInfo userInfo = UserManager.getIMUserInfo(presenter.getTargetId());
        //获取会话对象
        BmobIMConversation conversation = presenter.getConversation();
        if (null == conversation) {
            onBackPressed();
            return;
        }
        //标记当前会话的未读消息数为0
        conversation.setUnreadCount(0);
        BmobIM.getInstance().updateConversation(conversation);
        //发送进入聊天页面消息
        Bus.get().post(new InChatEvent(userInfo.getUserId()));
        //加载聊天列表
        chatListView.loadConversation(conversation);
        //设置会话给聊天控制器
        chatInputView.setConversation(conversation);
        //设置标题栏为目标用户名
        toolbar.setTitle(userInfo.getName());
        //取消当前会话对应的通知栏消息
        JNotify.build(getActivity())
                .cancel(presenter.getTargetId().hashCode());
        //设置权限
        chatInputView.setupPermission(getActivity());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getExtras();
        String targetId = bundle.getString(ChatActivity.KEY_TARGET_ID, "");
        if (!targetId.equals(presenter.getTargetId())) {
            //重新加载页面
            presenter = new ChatPresenter(getActivity(), this, bundle);
            //加载数据
            loadData();
        }
    }

    /**
     * 接受消息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveMessage(ReceiveMessageEvent event) {
        BmobIMMessage imMessage = event.getImMessage();
        String conversationId = imMessage.getConversationId();
        if (conversationId.equals(presenter.getTargetId())) {
            //添加消息到集合
            chatListView.addChatMessage(imMessage);
        }
    }

    @Override
    public void handleSuccess(String imagePath) {
        chatInputView.sendPhotoMessage(imagePath);
    }

    @Override
    public void onClick(View v) {
        //后退
        finish();
    }

    @Override
    public void onBackPressed() {
        if (!chatInputView.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }

    /**
     * 头像点击事件
     *
     * @param targetId
     */
    @Override
    public void avatarClick(String targetId) {
        Bundle bundle = new Bundle();
        bundle.putString(UserProfileActivity.KEY_USER_OBJECT_ID, targetId);
        ActivityJump.build(getActivity(), UserProfileActivity.class)
                .addBundle(bundle)
                .jump();
    }

    @Override
    public void imageClick(String imageUrl) {
        ImageGallery.gallery(getActivity(), new ArrayList<>(Arrays.asList(imageUrl)), 0);
    }

    @Override
    public void audioClick(String audioUrl) {
        AudioPlayerPopup.build(getActivity())
                .setAudioUrl(audioUrl)
                .showAsDropDown(toolbar);
    }

    @Override
    public void locationClick(double latitude, double longitude, String nickname, String address) {
        LocationSelect.showTarget(getActivity(),
                new double[]{latitude, longitude}, nickname + "\t在这里!", address);
    }

    @Override
    public void panelOrKeyboardChange(boolean isShowing) {
        chatListView.scrollToLastMessage(130);
    }

    @Override
    public void acquirePhoto() {
        ImageSelect.multiSelect(getActivity(), false, 9);
    }

    @Override
    public void acquireLocation() {
        LocationSelect.select(getActivity());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            //判断是否为位置选择返回
            if (LocationSelect.isRequestLocationResult(requestCode)) {
                double[] location = LocationSelect.getRequestLocation(data);
                String address = LocationSelect.getRequestLocationAddress(data);
                chatInputView.sendLocationMessage(location[0], location[1], address);
            }
            //判断是否为图片选择返回
            if (ImageSelect.isRequestImageResult(requestCode)) {
                List<String> imageList = ImageSelect.getRequestImage(data);
                if (null != imageList && imageList.size() > 0) {
                    presenter.handleImageList(imageList);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //下车
        Bus.getOff(this);
        //发送退出聊天页面的消息
        Bus.get().post(new InChatEvent(null));
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
        MobclickAgent.onPause(this);
    }
}